package com.zthz.douxing


class DomainClassInfoService {

    def sessionFactory
    def grailsApplication

    def getDomainClass(clazzName) {
        return grailsApplication.domainClasses.find {
            it.name == clazzName
        }
    }

    def getFieldColumnMap(clazz) {
        def fieldColumnMap = [:]
        def hibernateMetaClass = sessionFactory.getClassMetadata(clazz)
        def grailsDomainClass = getDomainClass(clazz.getSimpleName())
        def domainProps = grailsDomainClass.getProperties()

        domainProps.each { prop ->
            //get the property's name
            def propName = prop.getName()
            //please refer to the hibernate javadoc
            //http://www.hibernate.org/hib_docs/v3/api/org/hibernate/persister/entity/AbstractEntityPersister.html
            def columnProps = hibernateMetaClass.getPropertyColumnNames(propName)
            if (columnProps && columnProps.length > 0) {
                //get the columnname, which is stored into the first array
                def columnName = columnProps[0]
                fieldColumnMap[propName] = columnName
            }
        }
        return fieldColumnMap
    }
}
